import logging
import os
import re
import time
from logging.handlers import TimedRotatingFileHandler

from Common.handle_config import conf
from Common.handle_path import outputs_log_path

"""
1.初始化日志的名称和级别
2.定义日志格式
3.设置渠道
4.给渠道设置日志格式
"""


class MyLogger(logging.Logger):
    def __init__(self,file):
        super().__init__(conf.get("log", "name"), conf.get("log", "level"))

        # 日志格式
        fmt = '%(asctime)s %(name)s %(levelname)s %(filename)s-%(lineno)d line：%(message)s'
        fmt2='[%(asctime)s] [%(process)d] [%(levelname)s] - %(module)s.%(funcName)s (%(filename)s:%(lineno)d) - %(message)s'
        formatter = logging.Formatter(fmt2)


        # 设置渠道，控制台渠道
        handle1 = logging.StreamHandler()
        handle1.setFormatter(formatter)
        self.addHandler(handle1)

        #设置文件输出渠道
        if file:
            handle2=logging.FileHandler(file,encoding="utf-8")
            handle2.setFormatter(formatter)
            # self.addHandler(handle2)

            # interval 滚动周期，
            # when="MIDNIGHT", interval=1 表示每天0点为更新点，每天生成一个文件
            # “S”: Seconds,“M”: Minutes,“H”: Hours,“D”: Days,“W”: Week day (0=Monday),“midnight”: Roll over at midnight
            # backupCount  表示日志保存个数
            file_handler = TimedRotatingFileHandler(
                filename=file, when="MIDNIGHT", interval=1, backupCount=30,encoding="utf-8"
            )
            # filename="mylog" suffix设置，会生成文件名为mylog.2020-02-25.log
            file_handler.suffix = "%Y-%m-%d.log"
            # extMatch是编译好正则表达式，用于匹配日志文件名后缀
            # 需要注意的是suffix和extMatch一定要匹配的上，如果不匹配，过期日志不会被删除。
            file_handler.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}.log$")
            # 定义日志输出格式
            file_handler.setFormatter(formatter)
            self.addHandler(handle2)

if conf.getboolean("log","file_flag"):
    filename=conf.get("log","file_name")
    file_path=os.path.join(outputs_log_path,filename)
else:
    file_path=None

logger=MyLogger(file_path)

if __name__ == '__main__':
    while True:
        time.sleep(0.1)
        logger.info('哈哈哈')


